//@author A0121492M
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

public class ListCommand extends Command {
	public static enum DisplayDoneState {DONE, NOTDONE, BOTH};
	public boolean isListAll = false;
	
	public DisplayDoneState displayDoneStates = DisplayDoneState.BOTH;
	public String keyWordSearch = Task.EMPTY_STRING;
	
	public String titleFilter = Task.EMPTY_STRING;
	public Date startTimeFilter = Task.EMPTY_TIME;
	public Date endTimeFilter = Task.EMPTY_TIME;
	public String placeFilter = Task.EMPTY_STRING;
	public String projectFilter = Task.EMPTY_STRING;
	public String descriptionFilter = Task.EMPTY_STRING;
	    
	public MultipleTasksReply execute() throws TaskNotFoundException, PopupClosedException {
		ArrayList<Task> result = new ArrayList<Task>();
		if (this.isListAll == true) {
			result = filterByDoneState(Logic.loadedData);
		} else if (this.isListAll == false) {
			ArrayList<Task> hits = getFilterHits();
			result = filterByDoneState(hits);
		}
		Collections.sort(result);
		
		MultipleTasksReply r = new MultipleTasksReply();
		r.listOfTasks = result;
		return r;
	}

	private ArrayList<Task> getFilterHits() throws TaskNotFoundException {
		ArrayList<Task> hits = new ArrayList<Task>();
		if (keyWordSearch != Task.EMPTY_STRING) {
			hits = Logic.findTasksByKeyword(this.keyWordSearch);
		} else if (keyWordSearch == Task.EMPTY_STRING) {
			Task taskfilter = new Task();
			taskfilter.title = titleFilter;
			taskfilter.startTime = startTimeFilter;
			taskfilter.endTime = endTimeFilter;
			taskfilter.place = placeFilter;
			taskfilter.project = projectFilter;
			taskfilter.description = descriptionFilter;
			hits = Logic.filterTasks(taskfilter);
		}
		return hits;
	}

	private ArrayList<Task> filterByDoneState(ArrayList<Task> unfilteredList) {
		ArrayList<Task> result = new ArrayList<Task>();
		if (this.displayDoneStates == DisplayDoneState.BOTH) {
			return unfilteredList;
		} else if (this.displayDoneStates == DisplayDoneState.NOTDONE) {
			for (int i = 0; i < unfilteredList.size(); i++) {
				Task task = unfilteredList.get(i);
				if (!task.isDone) {
					result.add(task);
				}
			}
		} else if (this.displayDoneStates == DisplayDoneState.DONE) {
			for (int i = 0; i < unfilteredList.size(); i++) {
				Task task = unfilteredList.get(i);
				if (task.isDone) {
					result.add(task);
				}
			}
		}
		return result;
	}
}
